import useMenuStore from '@/store/menu';
import type { History } from 'history';
import type { FC } from 'react';
import { Router } from 'react-router-dom';
import renderRoutes from './renderRoute';
import staticRoutes from './routes';
import { RouteConfig } from './type';

const fixRoutes = (authRoutes: string[], routeList: RouteConfig[]) => {
  const routes: RouteConfig[] = [];
  routeList.forEach((i) => {
    const route: RouteConfig = {
      ...i,
      routes: undefined
    };
    const oChildRoutes = i.routes;
    if (oChildRoutes && oChildRoutes.length > 0) {
      const childRoutes = fixRoutes(authRoutes, oChildRoutes);
      route.routes = childRoutes;
    }
    if (i.meta?.auth) {
      if (authRoutes.includes(i.name)) {
        routes.push(route);
      }
    } else {
      routes.push(route);
    }
  });
  return routes;
};

/**
 * 生成路由组件模板
 * @param {History} history history 实例
 * @returns {FC} 路由组件
 */
export default function createRouteProvider(history: History): FC {
  return ({ children }) => {
    const { routes } = useMenuStore();
    const realRoutes = fixRoutes(routes, staticRoutes);
    return (
      <Router history={history}>
        {renderRoutes(realRoutes, {})}
        {children}
      </Router>
    );
  };
}
